<?php

namespace App\Http\Controllers\Home;

use App\Exceptions\BizException;
use App\Http\Controllers\Controller;
use App\Model\City;
use App\Model\Common;
use App\Model\Goods;
use App\Model\Order;
use App\Model\Province;
use App\Model\UserAddress;
use App\Model\WXPay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth'], ['except' => 'wxPayNotify']);
    }

    // 订单列表
    public function index(Request $request)
    {
        $user = Auth::user();
        $params = $request->all();

        $model = Order::with('orderDetails')->where('agent_id', $request->agent->id)->where('uid', $user->id)->where('status', '>', -1);
        isset($params['pay_status']) && $model->where('pay_status', $params['pay_status']);
        isset($params['status']) && $model->where('status', $params['status']);
        $list = $model->orderBy('id', 'desc')->paginate(15);

        if (isset($params['page']) && $params['page'] > 1) {
            return response()->json($list);
        } else {
            return view('home.' . $request->agent->tpl_id . '.order-list', [
                'list' => $list,
                'params' => $params,
                'payUri' => env('YFK_URL') . '/mobile/shoppay/js_api_call.php?url=' . urlencode($request->getSchemeAndHttpHost() . $request->getRequestUri()), // 主域名的支付地址
            ]);
        }
    }

    // 购物车
    public function cart(Request $request)
    {
        $totalMoney = 0;
        $cartGoods = empty($_COOKIE['cart_goods']) ? [] : json_decode($_COOKIE['cart_goods'], true);
        $goodsList = Goods::where('status', 1)->whereIn('id', array_keys($cartGoods))->get();
        foreach ($goodsList as $key => $goods) {
            $goodsList[$key]['cart_num'] = $cartGoods[$goods['id']];
            $totalMoney += $goods['price'] * $cartGoods[$goods['id']];
        }

        return view('home.' . $request->agent->tpl_id . '.cart', [
            'agent_id' => $request->agent->id,
            'goodsList' => $goodsList,
            'totalMoney' => $totalMoney,
        ]);
    }

    public function getCartGoods(Request $request)
    {
        $cartGoods = $request->input('goods') ? : [];
        $list = Goods::select(['id', 'name', 'origin_price', 'price', 'pic'])
            ->where('status', 1)
            ->where('agent_id', $request->agent->id)
            ->whereIn('id', array_keys($cartGoods))
            ->get();
        return response()->json($list);
    }

    public function del(Request $request)
    {
        Order::where('id', $request->input('id'))->update(['status' => -1]);
    }

    public function unifiedOrder(Request $request)
    {
        try {
            $order = Order::find($request->input('order_id'));

            // 重置订单号
            $order_num = date('ymdHis') . mt_rand(1000, 9999);
            Order::where('id', $order['id'])->update(['order_num' => $order_num]);

            $notify_url = $request->getSchemeAndHttpHost() . '/home/order/wxPayNotify'; // 支付结果通知地址
            $prepay_id = WXPay::unifiedOrder($order['openid'], $order_num, $order['money'] * 100, $notify_url, '支付测试');
            return response()->json(['status' => 1, 'info' => '下单成功', 'prepay_id' => $prepay_id]);
        } catch (\Exception $e) {
            return response()->json(['status' => 0, 'info' => $e->getMessage()]);
        }
    }

    public function confirmOrder(Request $request)
    {
        $user = \Auth::user();
        $params = $request->all();
        $cartGoods = empty($_COOKIE['cart_goods']) ? [] : json_decode($_COOKIE['cart_goods'], true);

        // 用户openid
        $openid = session('user_open_id');
        if (empty($openid) && $request->input('openid')) {
            $openid = $request->input('openid');
            session(['user_open_id' => $openid]);
        }

        if ($request->getMethod() == 'POST') {
            $notify_url = $request->getSchemeAndHttpHost() . '/home/order/wxPayNotify'; // 支付结果通知地址
            try {
                if (empty($params['address_id']))
                    throw new BizException('请选择收货信息');

                $order_id = Order::createOrder($openid, $cartGoods, $request->agent, $user, $params);
                $order = Order::find($order_id);

                // 微信统一下单
                $prepay_id = WXPay::unifiedOrder($openid, $order['order_num'], $order['money'] * 100, $notify_url);

                return response()->json([
                    'status' => 1,
                    'info' => '下单成功',
                    'prepay_id' => $prepay_id,
                ]);
            } catch (\Exception $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            // 微信openid
            if (empty($openid)) {
                $currentUrl = $request->getSchemeAndHttpHost() . $request->getRequestUri();
                $url = env('YFK_URL') . '/api/get_openid.php?state=' . urlencode($currentUrl);
                return redirect($url);
            }

            // 收货信息
            $provinces = Province::pluck('name', 'id');
            $addressList = UserAddress::where('uid', $user->id)->get()->toArray();
            foreach ($addressList as $k => $v) {
                $addressList[$k]['province'] = $provinces[$v['province_id']];
                $addressList[$k]['city'] = City::where('id', $v['city_id'])->value('name');
            }

            // 订单总额
            $totalMoney = 0;
            $goodsList = Goods::select(['id', 'price'])->where('status', 1)->whereIn('id', array_keys($cartGoods))->get();
            foreach ($goodsList as $goods) {
                $totalMoney += $goods['price'] * $cartGoods[$goods['id']];
            }

            return view('home.' . $request->agent->tpl_id . '.confirm-order', [
                'agent_id' => $request->agent->id,
                'addressList' => json_encode($addressList),
                'totalMoney' => $totalMoney,
                'openid' => $openid,
                'payUri' => env('YFK_URL') . '/mobile/shoppay/js_api_call.php?url=' . urlencode($request->getSchemeAndHttpHost() . '/home/order/index'), // 主域名的支付地址
            ]);
        }
    }

    // 微信支付成功的异步通知
    public function wxPayNotify()
    {
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $data = Common::simpleXmlToArray($xml);
        if (WXPay::checkSign($data)) { // 验签成功
            $order = Order::where('order_num', $data['out_trade_no'])->first();
            if ($order['pay_status'] == Order::PAY_STATUS_0) {
                Order::paySuccess($order);
            }

            return WXPay::returnNotifyXml(true); // 返回给微信结果
        } else {
            return WXPay::returnNotifyXml(false);
        }
    }
}